<?php

namespace app\admin\controller\short\chain;

use app\admin\service\StaticService;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\Loader;
use think\Log;
use think\Model;
use think\Request;

/**
 * 短链数据
 *
 * @icon fa fa-circle-o
 */
class Data extends Backend
{

    /**
     * Config模型对象
     * @var \app\admin\model\short\chain\Config
     */
    protected $model = null;
    protected $relationSearch = true;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\short\chain\Config;


    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(1);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
//        $group_all = Db::name('short_chain_group')->column('id');
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $filter = json_decode($this->request->get('filter'),true);

            $admin_id = $this->auth->id;
            if($admin_id == 1){
                $group_id = Db::name('short_chain_group')->column('id');
            }else{
                $group_id = Db::name('short_chain_group')->where('admin_id','=',$admin_id)->column('id');
            }
            $ids_arr = [];
            $config_all = Db::name('short_chain_config')->select();
            foreach($config_all as $k=>$v){
                $arr_group = explode(',',$v['group_id']);
                if(isset($filter['group_id'])){
                    if(in_array($filter['group_id'],$arr_group)){
                        $ids_arr[] = $v['id'];
                    }
                    $group_id_search = $filter['group_id'];
                }else{
                    if(array_intersect($group_id,$arr_group)){      //比较两个(或更多个)数组的值,并返回交集
                        $ids_arr[] = $v['id'];
                    }
                    $group_id_search = '';
                    unset($filter['group_id']);
                }
            }


            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            dump($where);
//            dump($sort);die;
            if($sort == 'config.pv'){
                $sort_new = 1;
                $sort = 'config.id';
            }elseif ($sort == 'config.uv'){
                $sort_new = 2;
                $sort = 'config.id';
            }elseif ($sort == 'config.ip'){
                $sort_new = 3;
                $sort = 'config.id';
            }else{
                $sort_new = 0;
            }
//            $sort =
//            dump($where);
//            dump($sort);die;
            $list = $this->model
                ->where('id','in',$ids_arr)
                ->order($sort, $order)
                ->paginate($limit);
            $data = $list->toArray();
            $data_new = [];
            $where = [];
            if($group_id_search){
                $where['group_id'] = $group_id_search;
            }
            if(isset($filter['createtime']) && $filter['createtime']){
                $date_arr = explode(' - ',$filter['createtime']);
                $where['createtime'] = ['between',$date_arr];
            }else{
                $date_arr = [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')];
                $where['createtime'] = ['between',[
                    date('Y-m-d 00:00:00'),
                    date('Y-m-d 23:59:59')
                ]];
            }

//            if(isset($filter['group_id']) && $filter['group_id']){
//                $group_id_new = $group_id_search;
//            }else{
//                $group_id_new = '';
//            }

//            dump($where);
//            dump($group_id);

//            dump($data['data']);die;
            $service = new StaticService();
            foreach($data['data'] as $k1=>$v1){
                $where['short_chain_id'] = $v1['id'];
                $where['createtime'] = ['between',[strtotime($date_arr[0]),strtotime($date_arr[1])]];
                $data_service = $service->getPv($group_id_search?:'',$v1['id'],date('Y-m-d',strtotime($date_arr[0])),date('Y-m-d',strtotime($date_arr[1])));
//                dump($v1['id']);
//                dump($data_service);die;
                $pv = $data_service['pv'];
                $uv = $data_service['uv'];
                $ip = $data_service['ip'];


                $orginal_url_arr = json_decode($v1['orginal_url'],true);
                $new = $v1['orginal_url'];
                if(is_array($orginal_url_arr)){
                    $x_arr = [];
                    foreach($orginal_url_arr as $k3=>$v3){
                        $x_arr[] = $v3['value'];
                    }
                    $new = implode(',',$x_arr);
                    $data['data'][$k1]['orginal_url'] = $new;
                }

                $data_new[] = [
                    'id'=>$v1['id'],
                    'title'=>$v1['title'],
                    'orginal_url'=>$new,
                    'short_url'=>$v1['short_url'],
                    'group_id'=>$v1['group_id'],
                    'pv'=>$pv,
                    'uv'=>$uv,
                    'ip'=>$ip,
                    'group_id_one'=>$v1['group_id'],
                    'createtime'=>$v1['createtime'],
                    'group_id_search'=>$group_id_search
                ];





            }
            if($sort_new == 1){
                $data_new = BubbleSort($data_new,'pv');
            }elseif ($sort_new == 2){
                $data_new = BubbleSort($data_new,'uv');
            }elseif ($sort_new == 3){
                $data_new = BubbleSort($data_new,'ip');
            }

            $result = array("total" => $list->total(), "rows" => $data_new);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add(){
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
//        dump($params);die;

        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if(isset($params['short_url'])){
            $short_explode = explode('/',$params['short_url']);
            if(!preg_match('/^(?![^a-zA-Z]+$)(?!\D+$)/',$short_explode[count($short_explode)-1])){
                $this->error(__('必须且只包含数字和字母', ''));
            }
            $has = \app\admin\model\short\chain\Config::where('short_url','=',$params['short_url'])->where('id','<>',$ids)->find();
            if($has){
                $this->error(__('唯一码重复', ''));
            }
        }


        $params = $this->preExcludeFields($params);
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null){
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        if(isset($params['short_url'])){
            $short_explode = explode('/',$params['short_url']);
            //----/^(?![^a-zA-Z]+$)(?!\D+$)/
            //----/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,10}$/
            if(!preg_match('/^(?![^a-zA-Z]+$)(?!\D+$)/',$short_explode[count($short_explode)-1])){
                $this->error(__('必须且只包含数字和字母', ''));
            }
            $has = \app\admin\model\short\chain\Config::where('short_url','=',$params['short_url'])->where('id','<>',$ids)->find();
            if($has){
                $this->error(__('唯一码重复', ''));
            }
            $params['key'] = $short_explode[count($short_explode)-1];
        }


        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }



    /**
     * Selectpage的实现方法
     *
     * 当前方法只是一个比较通用的搜索匹配,请按需重载此方法来编写自己的搜索逻辑,$where按自己的需求写即可
     * 这里示例了所有的参数，所以比较复杂，实现上自己实现只需简单的几行即可
     *
     */
    protected function selectpage(){
//        dump($this->request->request());
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");

        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");

        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");

        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 999999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
//        dump($field);die;
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }

            $fields = is_array($this->selectpageFields) ? $this->selectpageFields : ($this->selectpageFields && $this->selectpageFields != '*' ? explode(',', $this->selectpageFields) : []);

            //如果有primaryvalue,说明当前是初始化传值,按照选择顺序排序
            if ($primaryvalue !== null && preg_match("/^[a-z0-9_\-]+$/i", $primarykey)) {
                $primaryvalue = array_unique(is_array($primaryvalue) ? $primaryvalue : explode(',', $primaryvalue));
                //修复自定义data-primary-key为字符串内容时，给排序字段添加上引号
                $primaryvalue = array_map(function ($value) {
                    return '\'' . $value . '\'';
                }, $primaryvalue);

                $primaryvalue = implode(',', $primaryvalue);

                $this->model->orderRaw("FIELD(`{$primarykey}`, {$primaryvalue})");
            } else {
                $this->model->order($order);
            }

            $datalist = $this->model->where($where)
                ->page($page, $pagesize)
                ->select();

            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                if ($this->selectpageFields == '*') {
                    $result = [
                        $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                        $field      => isset($item[$field]) ? $item[$field] : '',
                    ];
                } else {
                    $result = array_intersect_key(($item instanceof Model ? $item->toArray() : (array)$item), array_flip($fields));
                }
                $result['pid'] = isset($item['pid']) ? $item['pid'] : (isset($item['parent_id']) ? $item['parent_id'] : 0);
                $list[] = $result;
            }
            if ($istree && !$primaryvalue) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null){
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
//        $filter = [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function ($v) {
                            return $v != '' && $v !== false && $v !== null;
                        })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }


    public function static_data(){
        $request = Request::instance();
        $group_id = $request->get('group_id');
        $config_id = $request->get('ids');
//        dump($request->get());die;
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(1);
        $date = date('Y-m-d');
//        $date_start = date('Y-m-d',strtotime('-6 days'));
        $date_start = date('Y-m-d');
        $date_range_param = [$date_start,$date];
        $date_range = printDates($date_start,$date);
//        dump($date_range_param);
//        dump($group_id);
//        dump($config_id);die;
        $data = $this->return_data($date_range_param,$group_id,$config_id);
//        dump($data);die;
        $where['short_chain_id'] = $config_id;
        if($group_id){
            $where['group_id'] = $group_id;
        }
//        dump($where);die;
        // 查询状态为1的用户数据 并且每页显示10条数据
        $list = Db::name('short_chain_statics')
            ->where($where)
            ->order('createtime','desc')
            ->paginate(200);
//        dump($list);die;
        $config_info = Db::name('short_chain_config')
            ->where('id',$config_id)
            ->find();

        $orginal_url_arr = json_decode($config_info['orginal_url'],true);

        if(is_array($orginal_url_arr)){
            $x_arr = [];
            foreach($orginal_url_arr as $k3=>$v3){
                $x_arr[] = $v3['value'];
            }
            $new = implode('<br>',$x_arr);
            $config_info['orginal_url'] = $new;
        }


//        $config_info['orginal_url'] =

//        $range_default = date('Y-m-d 00:00:00',strtotime('-6 days')).' - '.date('Y-m-d 23:59:59');
        $range_default = date('Y-m-d 00:00:00').' - '.date('Y-m-d 23:59:59');

        //今日访问次数，今日访问人数，总管理员数
        $this->view->assign([
            'times_today'         => $data['times_today'],
            'users_today'         => $data['users_today'],
            'ips_today'         => $data['ips_today'],
            'most_ip'         => $data['most_ip'],

            'times_30'         => array_values($data['times_30']),
            'users_30'         => array_values($data['users_30']),
            'ips_30'         => array_values($data['ips_30']),
            'times_24'         => array_values($data['times_24']),
            'area_34'         => $data['area_34'],
            'date_range'         => $date_range,
            'range_default'         => $range_default,

            'list'         => $list,
            'config_info'         => $config_info,

            'config_id'         => $config_id,
            'group_id'         => $group_id,
        ]);

        return $this->view->fetch();
    }

    public function get_data_by_range(){
        $request = Request::instance();
        $config_id = $request->post('config_id');
        $group_id = $request->post('group_id');
        $datarange = $request->post('daterange');
        $datarange_arr = explode(' - ',$datarange);
        $data = $this->return_data($datarange_arr,$group_id,$config_id);
        return $data;
//        dump($data);die;
    }

    public function return_data($datarange_arr,$group_id,$config_id){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->select(1);
//        $times_today = 0;
//        $users_today = 0;
//        $ips_today = 0;
        $times_30 = [];
        $users_30 = [];
        $ips_30 = [];
        $times_24 = [];
        $area_34 = [];
//        dump($datarange_arr);
//        dump($group_id);
//        dump($config_id);die;
//        $date_range = $datarange_arr;
        $date_range = printDates($datarange_arr[0],$datarange_arr[1]);
        $group_all = Db::name('short_chain_group')->column('id');

        $where['short_chain_id'] = $config_id;
        if($group_id){
            $where['group_id'] = $group_id;
        }
        $where['createtime'] = ['between',[strtotime($datarange_arr[0]),strtotime($datarange_arr[1])+86400-1]];

        //今日数据
        $service = new StaticService();
        $data_service = $service->getPv($group_id,$config_id,$datarange_arr[0],$datarange_arr[1]);

        $times_today = $data_service['pv'];
        $users_today = $data_service['uv'];
        $ips_today = $data_service['ip'];

//        dump($date_range);die;
//        dump('----------'.$times_today);die;
        //访问曲线
        foreach($date_range as $k1=>$v1){
            $where['createtime'] = ['between',[strtotime($v1),strtotime($v1)+86400-1]];
            $times_30[$v1] = Db::name('short_chain_statics')->where($where)->count();
            $users_30[$v1] = Db::name('short_chain_statics')->where($where)->group('cookie')->count();
            $ips_30[$v1]   = Db::name('short_chain_statics')->where($where)->group('ip')->count();
        }
        //24小时分布
//        $hours_24 = ['00','01','02','03','04','05','06','07','08','09','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];
        $hours_24 = ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23'];

        foreach($hours_24 as $k3=>$v3){
            $times_24[$v3] = 0;
            unset($where['createtime']);
            foreach($date_range as $k2=>$v2){
                $where['year'] = date('Y',strtotime($v2));
                $where['month'] = intval(date('m',strtotime($v2)));
                $where['day'] = intval(date('d',strtotime($v2)));
                $where['hour'] = $v3;
                $times_24[$v3] += Db::name('short_chain_statics')->where($where)->count();
            }
        }

        //地区分布
        $province_list = Db::name('district')->field('name')->where('type','=',1)->column('name');
        $province_value = [];
        foreach($province_list as $k5=>$v5){
            $province_value[$v5] = 0;
            unset($where['year']);
            unset($where['month']);
            unset($where['day']);
            unset($where['hour']);
            $where['createtime'] = ['between',[strtotime($datarange_arr[0]),strtotime($datarange_arr[1])+86400-1]];
            $where['province'] = $v5;
            $province_value[$v5] += Db::name('short_chain_statics')->where($where)->count();
            $area_34[] = [
                'name'=>$v5,
                'value'=>$province_value[$v5]?$province_value[$v5]:0,
            ];
        }
        //高频IP
        $most_ip = [];
        foreach($date_range as $k6=>$v6){
//            $config_id_arr = explode(',',$config_id);
            foreach($group_all as $kk5=>$vv5){
                if($redis->zRevRange('short_chain_IP_'.$v6.'_'.$vv5.'_'.$config_id,'0','9',true)){
                    $most_ip[] = $redis->zRevRange('short_chain_IP_'.$v6.'_'.$vv5.'_'.$config_id,'0','9',true);
                }

            }

        }
//        dump($most_ip);
        $most_ip_new = comm_sumarrs($most_ip);
//        dump($most_ip_new);
//        sort($most_ip_new);
//        dump($most_ip_new);
        $most_ip_new_2 = array_slice($most_ip_new,0,30);
//        dump($most_ip_new_2);die;
        return [
            'times_today'         => $times_today,
            'users_today'         => $users_today,
            'ips_today'         => $ips_today,
            'most_ip'         => $most_ip_new_2,
            'times_30'         => array_values($times_30),
            'users_30'         => array_values($users_30),
            'ips_30'         => array_values($ips_30),
            'times_24'         => array_values($times_24),
            'area_34'         => $area_34,
            'date_range'         => $date_range,
        ];
    }


}
